package com.xinggq.auth.service.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


/**
 * Redis配置类
 * 优化连接池配置和序列化设置
 *
 * @author xinggq
 * @since 2025-01-26
 */
@Slf4j
@Configuration
public class RedisConfig {

  /**
   * 配置RedisTemplate
   * 使用Jackson序列化
   */
  @Bean
  public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(connectionFactory);

    // Jackson序列化配置
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
        ObjectMapper.DefaultTyping.NON_FINAL);

    // 修复点：通过构造器传入 ObjectMapper
    Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(
        objectMapper, Object.class);

    // String序列化
    StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

    // 设置序列化方式
    // key采用String序列化
    template.setKeySerializer(stringRedisSerializer);
    // hash的key也采用String序列化
    template.setHashKeySerializer(stringRedisSerializer);
    // value采用jackson序列化
    template.setValueSerializer(jackson2JsonRedisSerializer);
    // hash的value采用jackson序列化
    template.setHashValueSerializer(jackson2JsonRedisSerializer);

    template.afterPropertiesSet();

    log.info("RedisTemplate配置完成 - 使用Jackson序列化");
    return template;
  }

  /**
   * 配置StringRedisTemplate
   * 专门用于字符串操作
   */
  @Bean
  public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory connectionFactory) {
    StringRedisTemplate template = new StringRedisTemplate();
    template.setConnectionFactory(connectionFactory);

    log.info("StringRedisTemplate配置完成");
    return template;
  }
}